#include "GameConfig.h"
#include "Config.h"
#include "pugixml.hpp"
#include <iostream>

using namespace std;
using namespace pugi;


GameConfig::GameConfig(void)
{
	_configData = NULL;
}


GameConfig::~GameConfig(void)
{
	CC_SAFE_RELEASE(_configData);
}

bool GameConfig::init()
{
	// Load anything
	setConfigData(CCDictionary::create());
	
	string data = getTextFromFile(PATH_CONFIG_BULLETS);
	_configData->setObject(ccs(data), CONFIG_BULLETS);
	data = getTextFromFile(PATH_CONFIG_WEAPONS);
	_configData->setObject(ccs(data), CONFIG_WEAPONS);
	data = getTextFromFile(PATH_CONFIG_PLANE);
	_configData->setObject(ccs(data), CONFIG_PLANE);
	data = getTextFromFile(PATH_CONFIG_ENEMY);
	_configData->setObject(ccs(data), CONFIG_ENEMY);
	data = getTextFromFile(PATH_CONFIG_PETS);
	_configData->setObject(ccs(data), CONFIG_PETS);
	data = getTextFromFile(PATH_CONFIG_ITEMS);
	_configData->setObject(ccs(data), CONFIG_ITEMS);
	data = getTextFromFile(PATH_CONFIG_LEVEL);
	_configData->setObject(ccs(data), CONFIG_PLAYERLEVEL);

	return true;
}

GameConfig* GameConfig::sharedGameConfig()
{
	if (!_instance)
		_instance = new GameConfig();
	return _instance;
}

std::string GameConfig::getTextFromFile( string fileName )
{
	string line = "";
    CCLog("Load config: %s", fileName.c_str());
	std::string path = CCFileUtils::sharedFileUtils()->fullPathForFilename(fileName.c_str());
	unsigned char* pBuffer = NULL;
	unsigned long bufferSize = 0;
	pBuffer = CCFileUtils::sharedFileUtils()->getFileData(path.c_str(), "r", &bufferSize);
	line = (char*)pBuffer;
	return line;
}

void GameConfig::clearGameConfig()
{
	delete _instance;
	_instance = NULL;
}

CCString* GameConfig::getConfigFromKey( int key )
{
	return dynamic_cast<CCString*>(_configData->objectForKey(key));
}

GameConfig* GameConfig::_instance = NULL;
